package com.hui.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hui.server.config.jwt.JwtProperties;
import com.hui.server.entity.Admin;
import com.hui.server.entity.AdminRole;
import com.hui.server.entity.MenuRole;
import com.hui.server.mapper.AdminMapper;
import com.hui.server.mapper.AdminRoleMapper;
import com.hui.server.service.AdminRoleService;
import com.hui.server.service.AdminService;
import com.hui.server.util.ClientIpAddrUtil;
import com.hui.server.util.jwt.JwtTokenUtil;
import com.hui.server.util.Result;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hui
 * @since 2022-03-31
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private MyUserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AdminRoleMapper adminRoleMapper;


    /**
     * 登录之后返回 token
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public Result<?> login(String username, String password, String code, HttpServletRequest request) {

        //验证码
        String ipAddress = ClientIpAddrUtil.getIpAddress(request);
        String captcha = stringRedisTemplate.opsForValue().get(ipAddress);
        if (StringUtils.isNullOrEmpty(captcha) || !code.equalsIgnoreCase(captcha)) {
            return Result.error(String.valueOf(HttpStatus.UNAUTHORIZED.value()), "验证码错误！");
        }

        //验证成功之后清除redis里的验证码
        stringRedisTemplate.delete(ipAddress);


        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return Result.error(String.valueOf(HttpStatus.UNAUTHORIZED.value()), "用户名或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            return Result.error(String.valueOf(HttpStatus.FORBIDDEN.value()), "账号被禁用");
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails.getUsername());
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", jwtProperties.getHeader());

        log.info("登录成功：{}", username);
        return Result.success(tokenMap);
    }

    /**
     * 获取当前登录用户信息
     *
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
    }


    /**
     * 获取所有操作员，除了已经登录的用户本身
     *
     * @return
     */
    @Override
    public Result<?> getAllAdminsByFuzzyQuery(String keywords) {
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        log.info("查询到登录的用户：{}", admin);
        List<Admin> list = adminMapper.getAllAdminsByFuzzyQuery(admin.getId(), keywords);
        return Result.success(list);
    }


    /**
     * 更新操作员角色，思路是先删除用户原有的角色id，再按照rids重新插入
     *
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = Exception.class)
    public Result<?> updateAdminRole(Integer adminId, Integer[] rids) throws SQLException {
        int delete = adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", adminId));
        log.info("成功删除数据条目：{}", delete);

        if (rids == null || rids.length == 0) {
            return Result.success("更新成功");
        }

        Integer result = adminRoleMapper.updateAdminRole(adminId, rids);
        log.info("成功插入数据条目：{}", result);

        if (rids.length == result) {
            return Result.success("更新成功");
        }

        log.error("更新数据库失败：{}", this.getClass());

        throw new SQLException("更新用户角色时发生异常，数据库回滚！传入的参数：rid：" + adminId + "，mids的长度：" + rids.length);
    }


    /**
     * 更新用户密码
     *
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public Result<?> updatePassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldPass, admin.getPassword())) {
            admin.setPassword(encoder.encode(pass));
            int i = adminMapper.updateById(admin);
            if (i == 1) {
                return Result.success();
            } else {
                return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "更新失败");
            }
        }

        return Result.error(String.valueOf(HttpStatus.FORBIDDEN.value()), "旧密码输入错误！");
    }

}
